package com.neuronrobotics.openigt;

import javax.swing.JLabel;
import javax.swing.JPanel;
//import com.neuronrobotics.sdk.common.Log;
import com.neuronrobotics.aim.gui.ImageControlPanel;
import com.neuronrobotics.aim.gui.MainGUI;
import com.neuronrobotics.sdk.genericdevice.GenericPIDDevice;
// import com.neuronrobotics.sdk.ui.ConnectionDialog;
//import com.neuronrobotics.aim.openigt.*;
// import com.neuronrobotics.aim.robot.*;
import net.miginfocom.swing.MigLayout;
import javax.swing.JTextField;
import javax.swing.JCheckBox;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.JButton;
//import org.medcare.igtl.tests.client.MyClientErrorManager;
//import org.medcare.igtl.tests.server.HaosOpenIGTServer;
//import org.medcare.igtl.tests.server.ProstateRobotKinematicModel;
import org.medcare.igtl.util.ErrorManager;

public class OpenIGTPanel extends JPanel {
	private MainGUI kinematicsGUI;
	private static final long serialVersionUID = 1L;
	private JTextField textFieldPort;
//	private JTextField textFieldAddress;
	
	private static MyClientErrorManager errorManager;
	public static HaosOpenIGTServer openIGTServer;
	private int port = 18944;
	private boolean openIGTconnected = false;
	public static  boolean networkControlEnabled =false;

	public OpenIGTPanel(MainGUI kinematicsGUI) {
		setKinematicsGUI(kinematicsGUI);
		this.setSize(new Dimension(1024, 768));
		setLayout(new MigLayout("", "[42.00px][344.00,grow][][][]",
				"[23px][][][][][][]"));

		JLabel lblControlMode = new JLabel("Mode :");
		add(lblControlMode, "cell 0 1");

		final JCheckBox chckbxLocalControl = new JCheckBox("Local Control");
		chckbxLocalControl.setSelected(true);
		add(chckbxLocalControl, "cell 1 1");

		final JCheckBox chckbxNetworkControl = new JCheckBox("Network Control");
		chckbxNetworkControl.setSelected(false);
		add(chckbxNetworkControl, "flowx,cell 1 1");
		// ///////////////////////////////////////////////////
		// event listener for check box NetworkControl
		chckbxNetworkControl.addActionListener(new ActionListener() {
		//	boolean enableCheckBox = true;

			public void actionPerformed(ActionEvent e) {
				// enableCheckBox=!enableCheckBox;
				chckbxNetworkControl.setSelected(true);
				networkControlEnabled=true;
				ImageControlPanel.tableZFrameRegistration.setEnabled(false);	
		//		ImageControlPanel.jButtonZFrameRegistration.setEnabled(true);
		//		ImageControlPanel.jButtonBaseinZFrameCalibration.setEnabled(true);
				chckbxLocalControl.setSelected(false);
				
				double[][] tableBaseinZFrameCalibrationRotationMatrix = { { 1, 0, 0 },
						{ 0, 1, 0}, { 0, 0, 1 }};
				double[] tableBaseinZFrameCalibrationPosVector ={0,-33.55,-219.24};				
				ImageControlPanel.tableBaseinZFrameCalibration.setTableData(tableBaseinZFrameCalibrationRotationMatrix, tableBaseinZFrameCalibrationPosVector);
				
			}
		});

		// event listener for check box LocalControl
		chckbxLocalControl.addActionListener(new ActionListener() {
			boolean enableCheckBox = true;

			public void actionPerformed(ActionEvent e) {
				networkControlEnabled=false;
				// enableCheckBox=!enableCheckBox;
				chckbxLocalControl.setSelected(enableCheckBox);
				// TODO tableZFrameRegistration has to be set as static, why?
				ImageControlPanel.tableZFrameRegistration.setEnabled(enableCheckBox);
			//	ImageControlPanel.jButtonZFrameRegistration.setEnabled(false);
			//	ImageControlPanel.jButtonBaseinZFrameCalibration.setEnabled(false);
				//ImageControlPanel.tableZFrameRegistration.setTableElement(2.257, 3, 1);
				chckbxNetworkControl.setSelected(!enableCheckBox);
			}
		});
		// ///////////////////////////////////////////////////

		JLabel lblPort = new JLabel("Port:");
		add(lblPort, "cell 0 3");

		textFieldPort = new JTextField();
		textFieldPort.setText("18944");
		textFieldPort.setSize(20, 12);
		add(textFieldPort, "cell 1 3");
		textFieldPort.setColumns(5);

		JLabel lblAddress = new JLabel("Address:");
		add(lblAddress, "cell 0 4");
		
		JLabel lblAddressDisplay = new JLabel("--.--.--.--");
		add(lblAddressDisplay, "cell 1 4");

		try {
			//Get an instance of InetAddress for the local computer
			InetAddress inetAddress = InetAddress.getLocalHost();

			//Get a string representation of the ip address
			String ipAddress = inetAddress.getHostAddress();	    
		    lblAddressDisplay.setText(ipAddress);
		} catch (UnknownHostException e) {
			System.err.println("cannot display IP");
		}
		
//		textFieldAddress = new JTextField();
//		textFieldAddress.setText("--.--.--.--");
//		add(textFieldAddress, "cell 1 4");
//		textFieldAddress.setColumns(10);

		JLabel lblCrc = new JLabel("CRC:");
		add(lblCrc, "cell 0 5");

		final JCheckBox chckbxCRCCheck = new JCheckBox("Check");
		chckbxCRCCheck.setSelected(true);
		add(chckbxCRCCheck, "flowx,cell 1 5");

		final JCheckBox chckbxCRCIgnore = new JCheckBox("Ignore");
		chckbxCRCIgnore.setSelected(false);
		add(chckbxCRCIgnore, "cell 1 5");

		// ///////////////////////////////////////////////////
		// event listener for check box chckbxCRCCheck
		chckbxCRCCheck.addActionListener(new ActionListener() {
			boolean enableCheckBox = true;

			public void actionPerformed(ActionEvent e) {
				// enableCheckBox=!enableCheckBox;
				chckbxCRCCheck.setSelected(enableCheckBox);
				chckbxCRCIgnore.setSelected(!enableCheckBox);
			}
		});

		// event listener for check box chckbxCRCIgnore
		chckbxCRCIgnore.addActionListener(new ActionListener() {
			boolean enableCheckBox = true;

			public void actionPerformed(ActionEvent e) {
				// enableCheckBox=!enableCheckBox;
				chckbxCRCIgnore.setSelected(enableCheckBox);
				chckbxCRCCheck.setSelected(!enableCheckBox);
			}
		});
		// ///////////////////////////////////////////////////

		final JButton btnConnectToNetwork = new JButton("Connect to Network");
		add(btnConnectToNetwork, "cell 1 6");
		btnConnectToNetwork.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try{
					if (openIGTconnected==false)
					{
						port = Integer.parseInt(textFieldPort.getText());
						btnConnectToNetwork.setText("Disconnect from Network");
						openIGTconnected = true;
						networkControlEnabled=true;
						startOpenIGT();
					}
					else
					{
						if (openIGTServer!=null)
						{
							closeOpenIGT();
							btnConnectToNetwork.setText("Connect to Network");
							openIGTconnected = false;
							networkControlEnabled=false;
						}
					}
					}catch (NumberFormatException event){
						System.err.println("Wrong Port Format!");
					}
			}
		});	
	} 


	public void setKinematicsGUI(MainGUI kinematicsGUI) {
		this.kinematicsGUI = kinematicsGUI;
	}

	public GenericPIDDevice getDevice() {
		return kinematicsGUI.getDevice();
	}

	public MainGUI getKinematicsGUI() {
		return kinematicsGUI;
	}

	public void startOpenIGT(){
	System.out.println("Starting with PID device");
	errorManager = new MyClientErrorManager();
	try {
		/// start OpenIGT communication
		//Log.enableDebugPrint(true);
		System.out.println("Starting IGT server");
		// MessageHandler.perform can a answer by using
		// ServerThread.sendBytes in perform method of MessageHandler		
		openIGTServer = new HaosOpenIGTServer(port, errorManager);
		System.out.println("Started IGT server");
	} catch (Exception e) {
		e.printStackTrace();
		errorManager.error("Server on port : " + port+ " Get an exception", e, ErrorManager.APPLICATION_EXCEPTION);
	}
	}
	
	public void closeOpenIGT(){
		//TODO 
		openIGTServer.getStatus();		
	}


	@SuppressWarnings("static-access")
	public void setNetworkControl(boolean networkControl) {
		this.networkControlEnabled = networkControl;
	}


	public boolean isNetworkControl() {
		return networkControlEnabled;
	}
}
